<!-- prettier-ignore -->
<template>
  <el-dialog :visible.sync="dialogVisible" title="创建任务" width="50%">

    <el-radio-group v-model="selectCard"  style="margin-bottom: 20px">
      <el-radio-button label="task" value="task">任务信息</el-radio-button>
      <el-radio-button label="rule" value="rule">质检规则</el-radio-button>
    </el-radio-group>

    <div v-show="selectCard === 'task'">
      <el-form label-width="120px">
        <el-form-item label="数据来源：">
          <el-radio-group v-model="source">
            <el-radio label="database">数据库</el-radio>
            <el-radio label="files">导入数据</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择数据：">
          <template v-if="source === 'database'">
            <el-select v-model="checkDataSource" style="width:100%">
              <el-option v-for="(item,index) in dataSourceOption" :key="index" :value="item.name">{{item.name}}</el-option>
            </el-select>
          </template>
          <template v-else>
            <div style="display: flex;justify-content: space-between">
              <el-upload
                :before-upload="beforeUpload"
                action=""
                class="upload-demo">
                <el-button size="small" style="margin-right:10px" type="primary">点击上传</el-button>
              </el-upload>
              <el-input v-model="fileName"></el-input>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="任务名称：">
          <el-input v-model="createParams.name"></el-input>
        </el-form-item>
        <el-form-item label="创建人：">
          <el-input v-model="createParams.user" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属单位：">
          <el-input v-model="createParams.unit" disabled></el-input>
        </el-form-item>
        <el-form-item label="数据范围：">
          <el-cascader v-model="dataSource" :props="cityProps" style="width: 100%">
          </el-cascader>
        </el-form-item>
        <el-form-item label="质检方案：">
          <el-select v-model="programme" style="width: 100%" @change="programChange">
            <el-option label="统一地址" value="unified"></el-option>
            <el-option label="楼栋地址" value="build"></el-option>
            <el-option label="户室地址" value="householdRoom"></el-option>
            <el-option label="村组地址" value="villageGroup"></el-option>
            <el-option label="非村组地址" value="nonVillageGroup"></el-option>
          </el-select>
          <br>
          <el-button type="text" @click="selectAllRules">自定义质检规则</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div v-show="selectCard === 'rule'">
      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" style="margin-left: 24px" @change="handleCheckAll">全选</el-checkbox>
      <el-row type="flex">
        <el-col :span="10">
          <wp-scrollbar :max-height="300" scrollbarColor="rgba(51,51,51,0.2)">
            <el-tree ref="tree" :data="rulesTree" default-expand-all highlight-current node-key="id" show-checkbox @check="treeCheck" @node-click="treeNodeClick"></el-tree>
          </wp-scrollbar>
        </el-col>
        <el-col :span="14">
          <p>详细描述</p>
          <div class="descript-box">{{descript}}</div>
        </el-col>
      </el-row>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="createTask">创建</el-button>
    </span>
  </el-dialog>
</template>

<script>
import axios from 'axios'
import rulesJson from '@/assets/rules.json'
export default {
  name: "taskCreate",
  data() {
    return {
      checkDataSource:'',
      dataSourceOption:[],
      fileName:'',
      dataSource:[],
      checkAll: false,
      isIndeterminate: false,
      selectCard: "task",
      source:'database',
      programme:'',
      rulesTree:[],
      descript:'',
      treeAllKeys:[],
      selectedKeys:null,
      programTreeKey:{ // 选择方案时，要从全部的keys中移除的项
        unified:[],
        build:['2','16','16-2','16-3','16-4'],
        householdRoom:['16','16-1','16-3','16-4'],
        villageGroup:['16','16-1','16-2','16-3'],
        nonVillageGroup:['16','16-1','16-2','16-4']
      },
      cityProps: {
        value: "name",
        label: "name",
        checkStrictly: true,
        children: "districts",
        lazy: true,
        lazyLoad: this.getCityProps,
      },
      createParams:{
        name:'',
        user:'李建',
        unit:'省政务服务和数据管理局',
        source:'',
        type:2,
        checkType:''
      }
    };
  },
  created(){
    this.rulesTree = rulesJson.qualityTest
    this.treeAllKeys = this.getKeys(this.rulesTree)
    this.getParticipleTask()
  },
  props: {
    createShow: {
      type: Boolean,
      default: true,
    },
  },
  methods: {
    async createTask(){
      this.createParams.source = this.dataSource.join(' / ')
      this.createParams.checkType = this.programme ? this.programme : '自定义'
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      const res = await axios.post(`${window.baseUrl}/address/task/create`,this.createParams)
      if(res.status === 200){
        loading.close()
        this.$message.success('任务创建成功')
        this.$parent.updateList()
        this.dialogVisible = false
      } else {
        this.$message.error('任务创建失败')
        loading.close()
      }
    },
    beforeUpload(file){
      this.fileName = file.name
      return false
    },
    // 获取城市信息
    async getCityProps(node, resolve) {
      let nodes = [];
      let keywords = ''
      if (node.level === 0) {
        keywords = '黄冈市'
      } else {
        keywords = node.value
      }
      let res = await axios.get(
        "https://restapi.amap.com/v3/config/district",
        {
          params: {
            keywords,
            subdistrict: 2,
            key: "4bb9d93c9b35ffdc9a5177d230394f23",
          },
        }
      );
      res.data.districts[0].districts.forEach((item) => {
        const leaf = !item.districts.length;
        nodes.push({ ...item,leaf });
      });
      resolve(nodes)
    },
    // 质检方案修改时从所有的keys中筛选掉一部分,并在tree上渲染需要选中的
    programChange(){
      const newSelected = this.treeAllKeys.filter(item => !this.programTreeKey[this.programme].includes(item))
      this.$refs.tree.setCheckedKeys(newSelected)
      this.treeCheck()
    },
    // 点击树的复选框时判断是否已经全部选择
    treeCheck(){
      this.selectedKeys = this.$refs.tree.getCheckedKeys()
      if (this.selectedKeys.length === 0){
        this.isIndeterminate = false
        this.checkAll = false
      } else if (this.selectedKeys.length < this.treeAllKeys.length){
        this.isIndeterminate = true
        this.checkAll = false
      } else if (this.selectedKeys.length === this.treeAllKeys.length){
        this.isIndeterminate = false
        this.checkAll = true
      }
    },
    // 设置全选和取消全选
    handleCheckAll(){
      this.isIndeterminate = false
      if (this.checkAll){
        this.$refs.tree.setCheckedKeys(this.treeAllKeys)
      } else {
        this.$refs.tree.setCheckedKeys([])
      }
    },
    treeNodeClick(data){
      this.descript = data.describe
    },
    // 从tree的data中获取所有的id
    getKeys(data) {
      let keys = []
      data.forEach(item => {
        keys.push(item.id);
        if (item.children && item.children.length > 0) {
          keys.push(...this.getKeys(item.children))
        }
      });
      return keys
    },
    // 点击自定义时默认全选所有的规则
    selectAllRules(){
      this.programme = ''
      this.$refs.tree.setCheckedKeys(this.treeAllKeys)
      this.selectCard = 'rule'
      this.checkAll = true
      this.isIndeterminate = false
    },
    // 获取分词任务作为数据的来源
    async getParticipleTask(){
      const res = await axios.get(`${window.baseUrl}/address/task/list`,{
        params:{
          page:1,
          size:30,
          type:1
        }
      })
      this.dataSourceOption = res.data.data.records
    },
  },
  computed: {
    dialogVisible: {
      get() {
        return this.createShow;
      },
      set(val) {
        this.$emit("update:createShow", val);
      },
    },
  },
};
</script>

<style lang="less">
.descript-box{
  width: 100%;
  height: 250px;
  border:1px solid #d3d3d3;
  padding: 15px;
  border-radius: 8px;
  white-space: pre-wrap;
}
</style>
